package com.ghl.springbootmysqlmasterslave.aop;

import com.ghl.springbootmysqlmasterslave.datasource.DBContextHolder;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

@Component
@Aspect
@Order(1)
public class DataSourceAop {

    private Logger logger = LoggerFactory.getLogger(DataSourceAop.class);

    /**
     * 注解声明切点表达式
     */
    @Pointcut("(execution(* com.ghl.springbootmysqlmasterslave.service..*.select*(..)) " +
            "|| execution(* com.ghl.springbootmysqlmasterslave.service..*.find*(..)) " +
            "|| execution(* com.ghl.springbootmysqlmasterslave.service..*.get*(..)))")
    public void readPointcut() {
    }

    @Pointcut("execution(* com.ghl.springbootmysqlmasterslave.service..*.insert*(..)) " +
            "|| execution(* com.ghl.springbootmysqlmasterslave.service..*.update*(..)) " +
            "|| execution(* com.ghl.springbootmysqlmasterslave.service..*.delete*(..)) ")
    public void writePointcut() {
    }


    /**
     * 前置通知.通知方法会在目标方法执行之前执行
     */
    @Before("readPointcut()")
    public void read() {
        logger.info("read operate");
        DBContextHolder.slave();
    }

    @Before("writePointcut()")
    public void write() {
        logger.info("write operate");
        DBContextHolder.master();
    }

    @After("writePointcut()||readPointcut()")
    public void clean() {
        logger.info("dataSource cleanAll");
        DBContextHolder.cleanAll();
    }


}
